package cn.anjubao.cp.api.service;

import cn.anjubao.cp.api.dto.CountFeeSlotsDto;
import cn.anjubao.cp.api.dto.LotInfoReqForm;
import cn.anjubao.cp.api.dto.SearchLotInfoReqForm;
import cn.anjubao.cp.api.feign.ParkingLotFeignClient;
import cn.anjubao.cp.api.mapper.ParkingLotSlotMapper;
import com.anjubao.parking.municipal.parkinglot.dto.ParkingLotDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Optional;

@Service
public class ParkingLotService {
    @Autowired
    private ParkingLotFeignClient parkingLotFeignClient;
    @Autowired
    private ParkingLotSlotMapper parkingLotSlotMapper;

    public List<ParkingLotDto> getLotInfo(LotInfoReqForm reqForm){
        List<ParkingLotDto> lotDtos=
                parkingLotFeignClient.findParkingLot(reqForm.getLatitude(),reqForm.getLongitude()).getResult();
        return this.getFeeSlots(lotDtos);
    }

    public List<ParkingLotDto> searchLotInfo(SearchLotInfoReqForm reqForm){
        List<ParkingLotDto> lotDtos=parkingLotFeignClient.
                searchParkinglot(reqForm.getNameOrAddress(),reqForm.getLatitude(),reqForm.getLongitude()).getResult();
        return this.getFeeSlots(lotDtos);
    }


    public  List<ParkingLotDto> getFeeSlots(List<ParkingLotDto> lotDtos){
        if (lotDtos==null || lotDtos.size()==0) return null;
        List<CountFeeSlotsDto> slotsDtos=parkingLotSlotMapper.countSlot(lotDtos);
        lotDtos.stream().forEach(item->{
            Optional<CountFeeSlotsDto> optional=slotsDtos.stream().
                    filter(j->j.getParkingLotId().equals(item.getId()))
                    .findFirst();
            if (!optional.isPresent()){
                item.setFreeSlots(0);
            }else {
                item.setFreeSlots(optional.get().getFeeSlots());
            }
        });
        return lotDtos;
    }
}
